package pilgun.eshop.domain;

import java.util.ArrayList;
import java.util.List;

public class Cart {
	List<ItemTuple> itemList = new ArrayList<ItemTuple>();
	
	public List<ItemTuple> getItemList() {
		return itemList;
	}
	public void setItemList(List<ItemTuple> itemList) {
		this.itemList = itemList;
	}
	public void addToItemList(Item item) {
		addToItemList(item, 1);
	}
	
	public void addToItemList(Item item, int stock) {
		boolean added = false;
		for (ItemTuple tuple:itemList){
			if (item.equals(tuple.item)){
				itemList.remove(tuple);
				ItemTuple newTuple = new ItemTuple(item, tuple.stock+stock);
				itemList.add(newTuple);
				added = true;
				break;
			}
		}
		if (!added){
			ItemTuple newTuple = new ItemTuple(item, 1);
			itemList.add(newTuple);
		}
	}
	
	@Override
	public String toString() {
		return "Cart [itemList=" + itemList + "]";
	}
	public boolean removeFromItemList(Item item){
		for (ItemTuple tuple:itemList){
			if (item.equals(tuple.item)){
				itemList.remove(tuple);
				return true;
			}
		}
		return false;
	}
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result
				+ ((itemList == null) ? 0 : itemList.hashCode());
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj){
			return true;
		}
		if (obj == null){
			return false;
		}
		if (getClass() != obj.getClass()){
			return false;
		}
		Cart other = (Cart) obj;
		if (itemList == null) {
			if (other.itemList != null){
				return false;
			}
		}else{
			if (!itemList.equals(other.itemList)){
				return false;
			}
		}
		return true;
	}
}
